from rest_framework import serializers
from rest_framework import exceptions
from storage.models import User, File, Access
from storage.utils import generateFileId


class RegisterSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField()
    first_name = serializers.CharField()
    last_name = serializers.CharField()

    def validate(self, data):
        email = data['email']
        if User.objects.filter(email=email).exists():
            raise exceptions.ValidationError({'email': 'Email уже занят.'})

        return data

    def create(self, validated_data):
        validated_data['username'] = validated_data['email']
        return User.objects.create_user(**validated_data)


class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField()

    def create(self, validated_data):
        if User.objects.get(email=validated_data['email']).check_password(validated_data['password']):
            return User.objects.filter(email=validated_data['email']).first()
        raise exceptions.AuthenticationFailed


class FileUploadSerializer(serializers.Serializer):
    files = serializers.ListField(child=serializers.FileField())

    def create(self, validated_data):
        user = validated_data['user']
        userFiles_name = []
        for j in Access.objects.filter(user=user, isOwner=True):
            userFiles_name.append(j.file.name)

        print(userFiles_name)
        response = []
        for file in validated_data['files']:
            if file.size / 1024 / 1024 > 2:
                response.append({
                    "success": False,
                    "message": "False",
                    "name": file.name,
                })

            extension = file.name.split('.')[-1]

            if extension not in ['doc', 'pdf', 'docx', 'zip', 'jpeg', 'jpg', 'png']:
                response.append({
                    "success": False,
                    "message": "False",
                    "name": file.name,
                })

            customname = file.name
            i = 1
            while customname in userFiles_name:
                customname = file.name
                customname = customname.replace(f".{extension}", '')
                customname = f"{customname} ({i}).{extension}"
                i += 1

            file.name = generateFileId(20)

            file_id = generateFileId(10)

            db_File = File.objects.create(file=file, file_id=file_id, name=customname)
            Access.objects.create(file=db_File, user=user, isOwner=True)

            response.append({
                "success": True,
                "message": "Success",
                "name": db_File.name,
                "url": db_File.get_url(),
                "file_id": db_File.file_id,
            })

        return response


class FileDownloadSerializer(serializers.Serializer):
    def create(self, validated_data):
        file_id = validated_data['file_id']
        return File.objects.get(file_id=file_id)


class FileDeleteSerializer(serializers.Serializer):
    def create(self, validated_data):
        file_id = validated_data['file_id']
        File.objects.get(file_id=file_id).delete()

        return {
           "success": True,
           "message": "File already deleted"
        }


class FileRenameSerilizer(serializers.Serializer):
    name = serializers.CharField()
    def create(self, validated_data):
        name = validated_data['name']
        file_id = validated_data['file_id']
        file = File.objects.get(file_id=file_id)

        user = validated_data['user']
        userFiles_name = []
        for j in user.files.all():
            userFiles_name.append(j.name)

        if name in userFiles_name:
            raise exceptions.ValidationError({'name': f'Уже есть файл с таким именем'})

        file.name = name

        file.save()

        return {
           "success": True,
           "message": "Renamed"
        }


class AddAccessSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def create(self, validated_data):
        email = validated_data['email']
        file_id = validated_data['file_id']

        user = User.objects.get(email=email)
        file = File.objects.get(file_id=file_id)

        if user:
            Access.objects.get_or_create(file=file, user=user)


        response = []

        for ac in Access.objects.filter(file=file):
            type = "co-author"
            if ac.isOwner:
                type = "author"

            response.append({
                'fullname': ac.user.get_full_name(),
                'email': ac.user.email,
                'type': type,
            })

        return response


class RemoveAccessSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def create(self, validated_data):
        email = validated_data['email']
        file_id = validated_data['file_id']

        user = User.objects.get(email=email)
        file = File.objects.get(file_id=file_id)

        if user:
            if not Access.objects.filter(user=user, file=file, isOwner=True).exists():
                print(user)
                Access.objects.get(file=file, user=user).delete()

        response = []

        for ac in Access.objects.filter(file=file):
            type = "co-author"
            if ac.isOwner:
                type = "author"

            response.append({
                'fullname': ac.user.get_full_name(),
                'email': ac.user.email,
                'type': type,
            })

        return response


class UserFilesSerializer(serializers.Serializer):

    def create(self, validated_data):
        user = validated_data['user']

        response = []

        for file in user.files.all():

            accesses = []
            for ac in Access.objects.filter(file=file):
                type = "co-author"
                if ac.isOwner:
                    type = "author"

                accesses.append({
                    'fullname': ac.user.get_full_name(),
                    'email': ac.user.email,
                    'type': type,
                })

            response.append({
                'file_id': file.file_id,
                'name': file.name,
                'url': file.get_url(),
                'accesses': accesses,
            })

        return response


class UserAccessesSerializer(serializers.Serializer):
    def create(self, validated_data):
        user = validated_data['user']

        response = []
        for ac in Access.objects.filter(user=user, isOwner=False):
            file = ac.file
            response.append({
                'file_id': file.file_id,
                'name': file.name,
                'url': file.get_url(),
            })
        return response
